package com.xqboss.apps.service.order.status.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.xqboss.apps.domain.order.OrderItem;
import com.xqboss.apps.domain.order.OrderMain;
import com.xqboss.apps.enums.order.OrderStatusEnum;
import com.xqboss.apps.enums.order.OrderTypeEnum;
import com.xqboss.apps.mapper.order.OrderMainMapper;
import com.xqboss.apps.service.box.BoxService;
import com.xqboss.apps.service.order.OrderItemService;
import com.xqboss.apps.service.order.OrderService;
import com.xqboss.apps.service.order.status.OrderStatusExecutor;
import com.xqboss.apps.service.order.type.OrderTypeExecutor;
import com.xqboss.common.exception.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Map;

/**
 * @author Trent
 * @date 2023/8/21
 */
@Component(value = OrderStatusEnum.Code.CLOSE)
public class OrderCloseExecutor extends OrderStatusExecutor {

    @Autowired
    @Lazy
    private OrderService orderService;

    @Autowired
    private OrderItemService orderItemService;

    @Autowired
    private BoxService boxService;

    @Autowired
    private Map<String, OrderTypeExecutor> orderTypeExecutor;
    
    @Override
    public void preValidate(OrderMain order) {
        if(order.getStatus() != OrderStatusEnum.UN_PAY){
            throw new ServiceException("订单状态异常");
        }
    }

    @Override
    public void execUpdate(OrderMain order) {
        order.setStatus(OrderStatusEnum.CLOSE);
        order.setCancelTime(LocalDateTime.now());
        boolean update = orderService.update(new LambdaUpdateWrapper<OrderMain>()
                .set(OrderMain::getStatus, order.getStatus())
                .set(OrderMain::getCancelTime, order.getCancelTime())
                .eq(OrderMain::getId, order.getId()));
        if(!update){
            throw new ServiceException("订单状态更新失败！");
        }
    }

    @Override
    public void postExec(OrderMain order) {
        OrderTypeExecutor executor = orderTypeExecutor.get(order.getOrderType().getCode());
        if(null != executor){
            executor.orderCancelPost(order);
        }
    }
}
